#include <Windows.h>
#include <tchar.h>
#include "windowsx.h"
#include "resource.h"

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0077"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			SendMessage(hDlg, WM_COMMAND, MAKEWPARAM(IDC_BTNREFRESH, BM_CLICK), 0);
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNADD:
				{
					TCHAR szName[MAX_PATH];
					TCHAR szValue[MAX_PATH];
					GetDlgItemText(hDlg, IDC_EDTNAME, szName, MAX_PATH);
					GetDlgItemText(hDlg, IDC_EDTVALUE, szValue, MAX_PATH);
					SetEnvironmentVariable(szName, szValue);
					break;
				}
				case IDC_BTNREFRESH:
				{
					HWND hListBox = GetDlgItem(hDlg, IDC_LIST1);
			
					for (int ii = ListBox_GetCount(hListBox) - 1; ii >= 0; ii--)
					{
						ListBox_DeleteString(hListBox, ii);
					}
										
					TCHAR* szEnvStrs = GetEnvironmentStrings();
					TCHAR* szPos = NULL;
					if (NULL != szEnvStrs && NULL != (szPos = _tcsstr(szEnvStrs, _T("::\\"))))
					{
						szPos += 4;
						while (NULL != *szPos)
						{
							ListBox_AddString(hListBox, szPos);
							szPos += _tcslen(szPos) + 1;
						}

						FreeEnvironmentStrings(szEnvStrs);
					}
					break;
				}
				case IDC_BTNREAD:
				{
					TCHAR szName[MAX_PATH];
					TCHAR szValue[MAX_PATH];
					GetDlgItemText(hDlg, IDC_EDTNAME2, szName, MAX_PATH);
					DWORD dwLen = GetEnvironmentVariable(szName, szValue, 0);
					if (0 != dwLen)
					{
						GetEnvironmentVariable(szName, szValue, dwLen);
						SetDlgItemText(hDlg, IDC_STCVALUE2, szValue);
					}
					break;
				}
			}

			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}